package com.market.web.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.upload.FormFile;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.ServletContextAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.market.Constants;
import com.market.constant.Constant;
import com.market.service.IBaseService;
import com.market.service.ICustomerService;
import com.market.service.IMessageService;
import com.market.service.IMsgBoardService;
import com.market.service.IOrdersService;
import com.market.service.IProCriService;
import com.market.service.IProductService;
import com.market.service.IScrollService;
import com.market.service.ISubproductService;
import com.market.service.ISupplierService;
import com.market.web.utils.ListUtils;
import com.opensymphony.xwork2.ActionSupport;


/**
 * Implementation of <strong>ActionSupport</strong> that contains 
 * convenience methods for subclasses.  For example, getting the current
 * user and saving messages/errors. This class is intended to
 * be a base class for all Action classes.
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class BaseAction2 extends ActionSupport implements ServletContextAware {
    
   
    
    private static final long serialVersionUID = 3525445612504421307L;

    private ServletContext context;  
    
    static final Logger logger = LoggerFactory.getLogger(BaseAction.class);
    
    /**
     * Constant for cancel result String
     */
    public static final String CANCEL = "cancel";

    /**
     * Transient log to prevent session synchronization issues - children can use instance for logging.
     */
    protected transient final Log log = LogFactory.getLog(getClass());


    /**
     * Indicator if the user clicked cancel
     */
    protected String cancel;

    /**
     * Indicator for the page the user came from.
     */
    protected String from;

    /**
     * Set to "delete" when a "delete" request parameter is passed in
     */
    protected String delete;

    /**
     * Set to "save" when a "save" request parameter is passed in
     */
    protected String save;


    /**
     * A message pre-populated with default data
     */
    protected SimpleMailMessage mailMessage;

    /**
     * Velocity template to use for e-mailing
     */
    protected String templateName;

    /**
     * Simple method that returns "cancel" result
     * @return "cancel"
     */
    public String cancel() {
        return CANCEL;
    }

    /**
     * Save the message in the session, appending if messages already exist
     * @param msg the message to put in the session
     */
    @SuppressWarnings("unchecked")
    protected void saveMessage(String msg) {
        List messages = (List) getRequest().getSession().getAttribute("messages");
        if (messages == null) {
            messages = new ArrayList();
        }
        messages.add(msg);
        getRequest().getSession().setAttribute("messages", messages);
    }

    /**
     * Convenience method to get the Configuration HashMap
     * from the servlet context.
     *
     * @return the user's populated form from the session
     */
    protected Map getConfiguration() {
        Map config = (HashMap) getSession().getServletContext().getAttribute(Constants.CONFIG);
        // so unit tests don't puke when nothing's been set
        if (config == null) {
            return new HashMap();
        }
        return config;
    }

    /**
     * Convenience method to get the request
     * @return current request
     */
    protected HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    /**
     * Convenience method to get the response
     * @return current response
     */
    protected HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    /**
     * Convenience method to get the session. This will create a session if one doesn't exist.
     * @return the session from the request (request.getSession()).
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }


    public void setMailMessage(SimpleMailMessage mailMessage) {
        this.mailMessage = mailMessage;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }

    /**
     * Convenience method for setting a "from" parameter to indicate the previous page.
     * @param from indicator for the originating page
     */
    public void setFrom(String from) {
        this.from = from;
    }

    public void setDelete(String delete) {
        this.delete = delete;
    }

    public void setSave(String save) {
        this.save = save;
    }
    
    public IBaseService getBaseService()
    {
        return baseService;
    }

    public void setBaseService(IBaseService baseService)
    {
        this.baseService = baseService;
    }

    public ISubproductService getSubproductService()
    {
        return subproductService;
    }

    public void setSubproductService(ISubproductService subproductService)
    {
        this.subproductService = subproductService;
    }

    public IMsgBoardService getMsgBoardService()
    {
        return msgBoardService;
    }

    public void setMsgBoardService(IMsgBoardService msgBoardService)
    {
        this.msgBoardService = msgBoardService;
    }

    public IOrdersService getOrdersService()
    {
        return ordersService;
    }

    public void setOrdersService(IOrdersService ordersService)
    {
        this.ordersService = ordersService;
    }

    public ICustomerService getCustomerService()
    {
        return customerService;
    }

    public void setCustomerService(ICustomerService customerService)
    {
        this.customerService = customerService;
    }

    public IProductService getProductService()
    {
        return productService;
    }

    public void setProductService(IProductService productService)
    {
        this.productService = productService;
    }
 



    public ServletContext getContext() {
        return context;
    }


    public void setContext(ServletContext context) {
        this.context = context;
    }
    
    public void setServletContext(ServletContext servletContext)
    {
        
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        scrollService = (IScrollService)wac.getBean("scrollServiceImpl");
        productService = (IProductService)wac.getBean("productServiceImpl");
        customerService = (ICustomerService)wac.getBean("customerServiceImpl");
        messageService = (IMessageService)wac.getBean("messageServiceImpl");
        ordersService = (IOrdersService)wac.getBean("ordersServiceImpl");
        supplierService = (ISupplierService)wac.getBean("supplierServiceImpl");
        proCriService = (IProCriService)wac.getBean("proCriServiceImpl");
        msgBoardService = (IMsgBoardService)wac.getBean("msgBoardServiceImpl");
        subproductService = (ISubproductService)wac.getBean("subproductServiceImpl");
        baseService = (IBaseService)wac.getBean("BaseServiceImpl");
        
        servletContext.setAttribute("category", Constant.category);
        java.util.List scrollList = scrollService.getScrollList();
        java.util.List l = ListUtils.convert(scrollList, com.market.bean.Product.class,
                com.market.web.form.ProductForm.class);
        servletContext.setAttribute("scroll", l);
        java.util.List newList = productService.getNewList(null, 3);
        servletContext.setAttribute("newProduct", ListUtils.convert(newList, com.market.bean.Product.class,
                com.market.web.form.ProductForm.class));
        servletContext.setAttribute("callBoard", Constant.callBoard);
        java.util.List disList = productService.getDiscountList(0, 3);
        servletContext.setAttribute("discount", ListUtils.convert(disList, com.market.bean.Product.class,
                com.market.web.form.ProductForm.class));
        java.util.List knowledge = getMessageService().findKnow(7);
        servletContext.setAttribute("knowledge", ListUtils.convert(knowledge, com.market.bean.Message.class,
                com.market.web.form.MessageForm.class));
        java.util.List news = getMessageService().findNews(7);
        servletContext.setAttribute("news", ListUtils.convert(news, com.market.bean.Message.class,
                com.market.web.form.MessageForm.class));
    }

    public int getCurPage()
    {
        String curPage = getRequest().getParameter("page");
        if(curPage==null)
        {
            return 0;
        }
        int p = 1;
        try
        {
            p = Integer.parseInt(curPage);
        }
        catch (Exception exception)
        {
            logger.error("",exception);
        }
        return p;
    }

    public IScrollService getScrollService()
    {
        return scrollService;
    }

    public void setScrollService(IScrollService scrollService)
    {
        this.scrollService = scrollService;
    }

    public ISupplierService getSupplierService()
    {
        return supplierService;
    }

    public void setSupplierService(ISupplierService supplierService)
    {
        this.supplierService = supplierService;
    }

    public IProCriService getProCriService()
    {
        return proCriService;
    }

    public void setProCriService(IProCriService proCriService)
    {
        this.proCriService = proCriService;
    }

    public IMessageService getMessageService()
    {
        return messageService;
    }

    public void setMessageService(IMessageService messageService)
    {
        this.messageService = messageService;
    }

    protected long getLong(String parameter)
    {
        long value = 0L;
        String str = getRequest().getParameter(parameter);
        if(str==null)
        {
            return value;
        }
        try
        {
            value = Long.parseLong(str);
        }
        catch (Exception exception)
        {
            logger.error("",exception);
        }
        return value;
    }

    protected void UploadImg(FormFile img, String name, String folder)
    {
        String path = getRequest().getRealPath(folder);
        InputStream ios = null;
        FileOutputStream fos = null;
        try
        {
            File f = new File(path + "/" + name);
            fos = new FileOutputStream(f);
            ios = img.getInputStream();
            byte buf[] = new byte[1024];
            for (int bytes = 0; (bytes = ios.read(buf)) != -1;)
                fos.write(buf, 0, bytes);

        }
        catch (FileNotFoundException e)
        {
            logger.error("",e);
        }
        catch (IOException e)
        {
            logger.error("",e);
        }
        finally
        {
            try
            {
                fos.close();
                ios.close();
            }
            catch (IOException e)
            {
                logger.error("",e);
            }
        }
        return;
    }

    protected boolean delImg(String filename, String folder)
    {
        try
        {
            String path;
            File f;
            path = getRequest().getRealPath(folder);
            f = null;
            f = new File(path + "/" + filename);
            return f.delete();
        }
        catch (Exception e)
        {
            logger.error("",e);
            return false;
        }
    }

    protected String getExeName(FormFile img)
    {
        String fileName = img.getFileName();
        String exeName = fileName.substring(fileName.indexOf("."));
        return exeName;
    }

    private WebApplicationContext wac;

    private IScrollService scrollService;

    private IProductService productService;

    private ICustomerService customerService;

    private IOrdersService ordersService;

    private ISupplierService supplierService;

    private IProCriService proCriService;

    private IMsgBoardService msgBoardService;

    private ISubproductService subproductService;

    private IMessageService messageService;

    private IBaseService baseService;
}
